<template>
	<view class="container">
		<!-- 顶部标题和筛选 -->
		<view class="header">
			<text class="title">学生签到系统</text>
			<picker class="grade-picker" mode="selector" :range="gradeOptions" range-key="label"
				@change="onGradeChange">
				<view class="picker">
					<text>{{gradeOptions[currentGradeIndex].label}}</text>
					<text class="icon">▼</text>
				</view>
			</picker>
		</view>

		<!-- 日期导航栏 -->
		<view class="date-navigator">
			<view class="nav-button prev" @click="changeDate(-1)">
				<text class="icon">◀</text> 前一天
			</view>
			<view class="current-date">
				<text class="date">{{ formattedChineseDate.split(' ')[0] }}</text>
				<text class="weekday">{{ formattedChineseDate.split(' ')[1] }}</text>
			</view>
			<view class="nav-button next" @click="changeDate(1)">
				后一天 <text class="icon">▶</text>
			</view>
		</view>

		<!-- 签到统计卡片 -->
		<view class="stats-card">
			<view class="stat-item">
				<text class="stat-value">{{checkedCount}}</text>
				<text class="stat-label">已选学生</text>
			</view>
			<view class="stat-item">
				<text class="stat-value">{{presentCount}}</text>
				<text class="stat-label">已签到</text>
			</view>
			<view class="stat-item">
				<text class="stat-value">{{absentCount}}</text>
				<text class="stat-label">未到</text>
			</view>
		</view>

		<!-- 操作按钮 -->
		<view class="action-buttons">
			<button class="btn check-all" @click="toggleSelectAll">{{isAllSelected ? '取消全选' : '全选'}}</button>
			<button class="btn present" @click="markPresent">签到</button>
			<button class="btn absent" @click="markAbsent">未到</button>
		</view>

		<!-- 学生列表 -->
		<scroll-view class="student-list" scroll-y>
			<view class="list-header">
				<text class="header-name">姓名</text>
				<text class="header-parent">家长</text>
				<text class="header-status">状态</text>
			</view>

			<checkbox-group @change="onStudentSelect">
				<view class="student-item" v-for="student in studentsWithCheckInfo" :key="student.userId">
					<label class="student-content">
						<checkbox class="student-checkbox" :value="String(student.userId)" :checked="student.checked" />
						<view class="avatar">{{student.studentName.charAt(0)}}</view>
						<view class="info">
							<text class="name">{{student.studentName}}</text>
							<text class="phone">{{student.phoneNumber}}</text>
						</view>
						<text class="parent">{{student.parentName}}</text>
						<view class="status-badge" :class="getStatusClass(student.status)">
							<text>{{getStatusText(student.status)}}</text>
						</view>
					</label>

					<!-- 打卡信息 -->
					<view class="check-info">
						<!-- 上午打卡信息 -->
						<view class="check-section morning">
							<view class="section-header">
								<text class="section-icon">🌞</text>
								<text class="section-title">上午打卡</text>
								<view v-if="student.morningChecks" class="check-status"
									:class="getCheckStatusClass(student.morningChecks[student.morningChecks.length - 1].status)">
									{{getCheckStatusText(student.morningChecks[student.morningChecks.length - 1].status)}}
								</view>
							</view>

							<view v-if="student.morningChecks">
								<view v-for="(check, index) in student.morningChecks" :key="index"
									class="check-details">
									<text class="check-time">{{formatTime(check.checkTime)}}</text>
									<text class="check-status" :class="getCheckStatusClass(check.status)">
										{{getCheckStatusText(check.status)}}
									</text>
									<text class="check-teacher">{{check.teacherName || '无记录'}}</text>
								</view>
							</view>
							<view v-else class="no-check">
								<text>上午未打卡</text>
							</view>
						</view>

						<!-- 下午打卡信息 -->
						<view class="check-section afternoon">
							<view class="section-header">
								<text class="section-icon">🌙</text>
								<text class="section-title">下午打卡</text>
								<view v-if="student.afternoonChecks" class="check-status"
									:class="getCheckStatusClass(student.afternoonChecks[student.afternoonChecks.length - 1].status)">
									{{getCheckStatusText(student.afternoonChecks[student.afternoonChecks.length - 1].status)}}
								</view>
							</view>

							<view v-if="student.afternoonChecks">
								<view v-for="(check, index) in student.afternoonChecks" :key="index"
									class="check-details">
									<text class="check-time">{{formatTime(check.checkTime)}}</text>
									<text class="check-status" :class="getCheckStatusClass(check.status)">
										{{getCheckStatusText(check.status)}}
									</text>
									<text class="check-teacher">{{check.teacherName || '无记录'}}</text>
								</view>
							</view>
							<view v-else class="no-check">
								<text>下午未打卡</text>
							</view>
						</view>
					</view>
				</view>
			</checkbox-group>

			<view v-if="students.length === 0" class="empty-tip">
				<text>暂无学生数据</text>
			</view>

			<view v-if="isFetchingRecords" class="progress-tip">
				<text>正在获取打卡记录 ({{ fetchedCount }}/{{ students.length }})</text>
				<view class="progress-bar">
					<view class="progress" :style="{width: `${(fetchedCount / students.length) * 100}%`}"></view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';

	export default {
		data() {
			return {
				gradeOptions: [{
						label: '一年级',
						value: '一年级'
					},
					{
						label: '二年级',
						value: '二年级'
					},
					{
						label: '三年级',
						value: '三年级'
					},
					{
						label: '四年级',
						value: '四年级'
					},
					{
						label: '五年级',
						value: '五年级'
					},
					{
						label: '六年级',
						value: '六年级'
					}
				],
				currentGradeIndex: 0,
				students: [],
				checkRecords: [],
				currentDate: new Date(),
				isFetchingRecords: false,
				fetchedCount: 0,
				attendanceRecords: {},
				currentTeacher: {
					id: '1',
					name: '李老师'
				}
			}
		},
		computed: {
			checkedCount() {
				return this.students.filter(s => s.checked).length;
			},
			presentCount() {
				return this.students.filter(s => s.status === 'present').length;
			},
			absentCount() {
				return this.students.filter(s => s.status === 'absent').length;
			},
			isAllSelected() {
				return this.students.length > 0 && this.students.every(s => s.checked);
			},
			formattedChineseDate() {
				const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
				const year = this.currentDate.getFullYear();
				const month = this.currentDate.getMonth() + 1;
				const day = this.currentDate.getDate();
				const weekday = weekdays[this.currentDate.getDay()];
				return `${year}年${month}月${day}日 ${weekday}`;
			},
			formattedDate() {
				const year = this.currentDate.getFullYear();
				const month = String(this.currentDate.getMonth() + 1).padStart(2, '0');
				const day = String(this.currentDate.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			studentsWithCheckInfo() {
				return this.students.map(student => {
					// 获取该学生所有打卡记录（按时间排序）
					const allRecords = this.checkRecords
						.filter(record => String(record.studentId) === String(student.userId))
						.sort((a, b) => new Date(a.checkTime) - new Date(b.checkTime));

					// 分离上午和下午的记录（取各自最新的记录）
					const morningChecks = allRecords.filter(r => r.checkType === 1);
					const afternoonChecks = allRecords.filter(r => r.checkType === 2);

					return {
						...student,
						// 显示上午所有记录（或最新一条）
						morningChecks: morningChecks.length > 0 ? morningChecks : null,
						// 显示下午所有记录（或最新一条）
						afternoonChecks: afternoonChecks.length > 0 ? afternoonChecks : null,
						// 保留原有单个最新记录（兼容旧代码）
						morningCheck: morningChecks.length > 0 ? morningChecks[morningChecks.length - 1] : null,
						afternoonCheck: afternoonChecks.length > 0 ? afternoonChecks[afternoonChecks.length - 1] :
							null
					};
				});
			},
			// 判断当前是上午还是下午 (上午: 0:00-12:00, 下午: 12:00-24:00)
			currentCheckType() {
				const hours = new Date().getHours();
				return hours < 12 ? 1 : 2;
			},
			currentCheckRemark() {
				return this.currentCheckType === 1 ? '上午到校' : '下午到校';
			}
		},
		onLoad() {
			this.loadStudents();
		},
		methods: {
			onGradeChange(e) {
				this.currentGradeIndex = e.detail.value;
				this.loadStudents();
			},

			loadStudents() {
				uni.showLoading({
					title: '加载中...'
				});
				const grade = this.gradeOptions[this.currentGradeIndex].value;

				uni.request({
					url: globalVariable + "/getStudentsByGrade",
					method: 'GET',
					data: {
						grade
					},
					success: (res) => {
						if (res.data.status === 1) {
							this.students = res.data.data.map(student => ({
								...student,
								checked: false,
								status: this.attendanceRecords[student.userId] || 'unmarked'
							}));
							this.fetchCheckRecordsOneByOne();
						}
					},
					complete: () => uni.hideLoading()
				});
			},

			async fetchCheckRecordsOneByOne() {
				this.isFetchingRecords = true;
				this.fetchedCount = 0;
				this.checkRecords = [];

				const batchSize = 3;
				const totalStudents = this.students.length;

				for (let i = 0; i < totalStudents; i += batchSize) {
					const batch = this.students.slice(i, i + batchSize);
					const promises = batch.map(student => this.fetchSingleCheckRecord(student.userId));

					try {
						await Promise.all(promises);
						this.fetchedCount = Math.min(i + batchSize, totalStudents);
					} catch (error) {
						console.error('获取打卡记录出错:', error);
					}
				}

				this.isFetchingRecords = false;
			},

			fetchSingleCheckRecord(studentId) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: globalVariable + "/getStudentCheckByIdDate",
						method: 'GET',
						data: {
							date: this.formattedDate,
							studentId: studentId
						},
						success: (res) => {
							if (res.data.status === 1 && res.data.data) {
								const records = res.data.data;
								records.forEach(record => {
									if (record) {
										record.studentId = String(record.studentId);
										this.checkRecords.push(record);
									}
								});
							}
							resolve();
						},
						fail: (err) => {
							console.error('获取打卡记录失败:', err);
							reject(err);
						}
					});
				});
			},

			changeDate(days) {
				const newDate = new Date(this.currentDate);
				newDate.setDate(newDate.getDate() + days);
				this.currentDate = newDate;
				this.fetchCheckRecordsOneByOne();
			},

			onStudentSelect(e) {
				const checkedIds = e.detail.value.map(id => parseInt(id));
				this.students = this.students.map(student => ({
					...student,
					checked: checkedIds.includes(student.userId)
				}));
			},

			toggleSelectAll() {
				const shouldSelectAll = !this.isAllSelected;
				this.students = this.students.map(student => ({
					...student,
					checked: shouldSelectAll
				}));
			},

			markPresent() {
				// 过滤出已选且未标记为present的学生
				const selectedStudents = this.students.filter(s =>
					s.checked && s.status !== 'present'
				);

				if (selectedStudents.length === 0) {
					let msg = '请先选择学生';
					if (this.checkedCount > 0) {
						msg = '选中的学生已经签到，无需重复操作';
					}
					uni.showToast({
						title: msg,
						icon: 'none'
					});
					return;
				}

				this.markStudents(1, '签到成功');
			},

			markAbsent() {
				// 过滤出已选且未标记为absent的学生
				const selectedStudents = this.students.filter(s =>
					s.checked && s.status !== 'absent'
				);

				if (selectedStudents.length === 0) {
					let msg = '请先选择学生';
					if (this.checkedCount > 0) {
						msg = '选中的学生已经标记为未到，无需重复操作';
					}
					uni.showToast({
						title: msg,
						icon: 'none'
					});
					return;
				}

				this.markStudents(0, '已标记未到');
			},

			markStudents(status, successMsg) {
				// 准备打卡数据
				const checkTime = new Date().toISOString().replace('T', ' ').substring(0, 19);
				const checkType = this.currentCheckType;
				const remark = this.currentCheckRemark;

				// 更新本地状态
				const updatedStudents = [];
				this.students = this.students.map(student => {
					if (student.checked) {
						// 只更新状态不同的学生
						const currentStatus = this.attendanceRecords[student.userId];
						if ((status === 1 && currentStatus !== 'present') ||
							(status === 0 && currentStatus !== 'absent')) {

							this.attendanceRecords[student.userId] = status === 1 ? 'present' : 'absent';

							updatedStudents.push({
								studentId: student.userId,
								studentName: student.studentName,
								grade: student.grade,
								teacherId: this.currentTeacher.id,
								teacherName: this.currentTeacher.name,
								checkType: checkType,
								checkTime: checkTime,
								remark: remark,
								status: status
							});

							return {
								...student,
								status: status === 1 ? 'present' : 'absent',
								checked: false
							};
						}
						return {
							...student,
							checked: false
						};
					}
					return student;
				});

				if (updatedStudents.length === 0) {
					uni.showToast({
						title: '没有需要更新的记录',
						icon: 'none'
					});
					return;
				}

				// 调用API更新签到状态
				uni.request({
					url: globalVariable + "/updateAttendance",
					method: 'POST',
					data: {
						checkRecords: updatedStudents
					},
					success: (res) => {
						if (res.data.status === 1) {
							uni.showToast({
								title: successMsg,
								icon: 'success'
							});
							// 刷新打卡记录
							this.fetchCheckRecordsOneByOne();
						} else {
							uni.showToast({
								title: '操作失败',
								icon: 'none'
							});
						}
					},
					fail: () => {
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						});
					}
				});
			},
			getStatusClass(status) {
				return {
					'unmarked': status === 'unmarked',
					'present': status === 'present',
					'absent': status === 'absent'
				};
			},

			getStatusText(status) {
				const statusMap = {
					'unmarked': '未签到',
					'present': '已签到',
					'absent': '未到'
				};
				return statusMap[status] || '未知';
			},

			getCheckStatusClass(status) {
				return {
					'checked': status === 1,
					'absent': status === 0,
					'unchecked': status === null || status === undefined
				};
			},

			getCheckStatusText(status) {
				return status === 1 ? '正常' : status === 0 ? '请假' : '未打卡';
			},

			formatTime(timeString) {
				if (!timeString) return '';
				try {
					const timePart = timeString.split(' ')[1];
					return timePart ? timePart.substring(0, 5) : '';
				} catch (e) {
					return '';
				}
			}
		}
	}
</script>

<style scoped>
	/* 保持原 有的样式不变 */
	.container {
		padding: 20rpx;
		background-color: #f8f8f8;
		min-height: 100vh;
	}

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}

	.grade-picker {
		background-color: #fff;
		border-radius: 50rpx;
		padding: 10rpx 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.picker {
		display: flex;
		align-items: center;
	}

	.icon {
		font-size: 24rpx;
		margin-left: 10rpx;
		color: #666;
	}

	.date-navigator {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		background-color: #fff;
		border-radius: 10rpx;
		padding: 15rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.nav-button {
		font-size: 28rpx;
		color: #666;
		display: flex;
		align-items: center;
	}

	.current-date {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.date {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
	}

	.weekday {
		font-size: 24rpx;
		color: #666;
	}

	.stats-card {
		background: linear-gradient(135deg, #6B73FF, #4D59FF);
		border-radius: 20rpx;
		padding: 30rpx;
		display: flex;
		justify-content: space-between;
		margin-bottom: 30rpx;
		color: white;
		box-shadow: 0 8rpx 20rpx rgba(77, 89, 255, 0.2);
	}

	.stat-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.stat-value {
		font-size: 48rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	.stat-label {
		font-size: 24rpx;
		opacity: 0.9;
	}

	.action-buttons {
		display: flex;
		justify-content: space-between;
		margin-bottom: 30rpx;
	}

	.check-details {
		display: flex;
		justify-content: space-between;
		padding: 8rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
		font-size: 24rpx;
	}

	.check-details:last-child {
		border-bottom: none;
	}

	.check-time {
		width: 30%;
		color: #666;
	}

	.check-status {
		width: 20%;
		text-align: center;
		padding: 2rpx 8rpx;
		border-radius: 20rpx;
		font-size: 22rpx;
	}

	.check-status.checked {
		background-color: #E8F5E9;
		color: #4CAF50;
	}

	.check-status.absent {
		background-color: #FFEBEE;
		color: #F44336;
	}

	.check-teacher {
		width: 40%;
		text-align: right;
		color: #999;
	}

	.btn {
		flex: 1;
		margin: 0 10rpx;
		border-radius: 50rpx;
		font-size: 28rpx;
		height: 80rpx;
		line-height: 80rpx;
		color: white;
		border: none;
	}

	.check-all {
		background-color: #999;
	}

	.present {
		background-color: #4CAF50;
	}

	.absent {
		background-color: #F44336;
	}

	.student-list {
		background-color: white;
		border-radius: 20rpx;
		padding: 0 20rpx;
		max-height: 70vh;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.list-header {
		display: flex;
		justify-content: space-between;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #eee;
		font-size: 28rpx;
		color: #999;
	}

	.header-name {
		width: 30%;
	}

	.header-parent {
		width: 25%;
		text-align: center;
	}

	.header-status {
		width: 20%;
		text-align: right;
	}

	.student-item {
		border-bottom: 1rpx solid #f5f5f5;
		padding-bottom: 20rpx;
	}

	.student-item:last-child {
		border-bottom: none;
	}

	.student-content {
		display: flex;
		align-items: center;
		padding: 25rpx 0;
	}

	.student-checkbox {
		margin-right: 20rpx;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-right: 20rpx;
		background-color: #6B73FF;
		color: white;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 36rpx;
		font-weight: bold;
	}

	.info {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.name {
		font-size: 30rpx;
		color: #333;
		margin-bottom: 5rpx;
	}

	.phone {
		font-size: 24rpx;
		color: #999;
	}

	.parent {
		width: 25%;
		text-align: center;
		font-size: 28rpx;
		color: #666;
	}

	.status-badge {
		width: 20%;
		padding: 8rpx 0;
		border-radius: 50rpx;
		font-size: 24rpx;
		text-align: center;
	}

	.status-badge.unmarked {
		background-color: #f5f5f5;
		color: #999;
	}

	.status-badge.present {
		background-color: #E8F5E9;
		color: #4CAF50;
	}

	.status-badge.absent {
		background-color: #FFEBEE;
		color: #F44336;
	}

	.check-info {
		margin-left: 120rpx;
		border-top: 1rpx dashed #eee;
		padding-top: 15rpx;
	}

	.check-section {
		margin-bottom: 15rpx;
	}

	.section-header {
		display: flex;
		align-items: center;
		margin-bottom: 10rpx;
	}

	.section-icon {
		margin-right: 10rpx;
		font-size: 28rpx;
	}

	.section-title {
		font-size: 26rpx;
		color: #666;
		margin-right: 15rpx;
	}

	.check-status {
		font-size: 24rpx;
		padding: 4rpx 12rpx;
		border-radius: 20rpx;
	}

	.check-status.checked {
		background-color: #E8F5E9;
		color: #4CAF50;
	}

	.check-status.absent {
		background-color: #FFEBEE;
		color: #F44336;
	}

	.check-status.unchecked {
		background-color: #f5f5f5;
		color: #999;
	}

	.check-details {
		display: flex;
		justify-content: space-between;
		font-size: 24rpx;
		color: #666;
	}

	.check-time,
	.check-teacher {
		flex: 1;
	}

	.no-check {
		font-size: 24rpx;
		color: #999;
	}

	.empty-tip {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 60rpx 0;
	}

	.empty-tip text {
		color: #999;
		font-size: 28rpx;
	}

	.progress-tip {
		padding: 20rpx 0;
		text-align: center;
		font-size: 26rpx;
		color: #666;
	}

	.progress-bar {
		height: 6rpx;
		background-color: #eee;
		border-radius: 3rpx;
		margin-top: 10rpx;
	}

	.progress {
		height: 100%;
		background-color: #4D59FF;
		border-radius: 3rpx;
		transition: width 0.3s;
	}
</style>